// See http://iphonedevwiki.net/index.php/Logos

#import "WeChatHeaders.h"
#import "WeChatRedEnvolopParamQueue.h"

@interface NewSettingViewController: UIViewController
@end

%hook NewSettingViewController


- (void) viewDidLoad {
%orig;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

%new
- (void) keyBoardWillShow:(NSNotification *)noti {
UIView *view = self.view;
CGRect keyBoardRect = [noti.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
view.frame = CGRectMake(0, -keyBoardRect.size.height, UIScreen.mainScreen.bounds.size.width, UIScreen.mainScreen.bounds.size.height);
}

%new
- (void) keyBoardWillHide:(NSNotification *)noti {
UIView *view = self.view;
view.frame = CGRectMake(0, 0, UIScreen.mainScreen.bounds.size.width, UIScreen.mainScreen.bounds.size.height);
}

%end


%hook MMTableViewInfo

%new
- (void) onSwitchChange:(UISwitch *)switchView {
    [LFDefault setBool:switchView.on forKey:LFSWITCH];
    [LFDefault synchronize];
    [MSHookIvar<UITableView *>(self,"_tableView") reloadData];
}

%new
- (void) onTextFieldChange:(UITextField *)tf {
    [LFDefault setValue:tf.text forKey:LFWAITTIME];
    [LFDefault synchronize];
}

- (id)tableView:(UITableView *)tableView cellForRowAtIndexPath:(id)arg2 {
    BOOL flag = [self numberOfSectionsInTableView:tableView] - 1 == [arg2 section];
    if ([tableView.nextResponder.nextResponder isKindOfClass:%c(NewSettingViewController)] && flag) {
        UITableViewCell *cell;
        if ([arg2 row] == 0) {
        static NSString *switchCell = @"switchCell";
        cell = [tableView dequeueReusableCellWithIdentifier:switchCell];
        if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:switchCell];
        cell.backgroundColor = [UIColor whiteColor];
        }
        cell.textLabel.text = @"自动抢红包";
        UISwitch *switchView = [[UISwitch alloc] init];
        [switchView addTarget:self action:@selector(onSwitchChange:) forControlEvents:UIControlEventValueChanged];
        switchView.on = [LFDefault boolForKey:LFSWITCH];
        cell.accessoryView = switchView;
        if (switchView.on) {
        cell.imageView.image = [UIImage imageNamed:@"unlocked"];
        } else {
        cell.imageView.image = [UIImage imageNamed:@"locked"];
        }
        } else{
        static NSString *switchCell = @"waitCell";
        cell = [tableView dequeueReusableCellWithIdentifier:switchCell];
        if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:switchCell];
        cell.backgroundColor = [UIColor whiteColor];
        }
        cell.textLabel.text = @"等待时间（秒）";
        UITextField *tf = [[UITextField alloc] initWithFrame:CGRectMake(0, 4, 100, 36)];
        [tf addTarget:self action:@selector(onTextFieldChange:) forControlEvents:UIControlEventEditingChanged];
        tf.borderStyle = UITextBorderStyleRoundedRect;
        tf.keyboardType = UIKeyboardTypeDecimalPad;
        tf.returnKeyType = UIReturnKeyDone;
        tf.text = [LFDefault valueForKey:LFWAITTIME];
        cell.accessoryView = tf;
        cell.imageView.image = [UIImage imageNamed:@"clock"];
        }
        return cell;
    }
    return %orig;
}
- (double)tableView:(UITableView *)tableView heightForRowAtIndexPath:(id)arg2 {
    BOOL flag = [self numberOfSectionsInTableView:tableView] - 1 == [arg2 section];
    if ([tableView.nextResponder.nextResponder isKindOfClass:%c(NewSettingViewController)] && flag) {
        return 44;
    }
    return %orig;
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    BOOL flag = [self numberOfSectionsInTableView:tableView] - 1 == section;
    if ([tableView.nextResponder.nextResponder isKindOfClass:%c(NewSettingViewController)] && flag) {
        return %orig + 2;
    }
    return %orig;
}
- (long long)numberOfSectionsInTableView:(UITableView *)tableView{
    if ([tableView.nextResponder.nextResponder isKindOfClass:%c(NewSettingViewController)]) {
        return %orig + 1;
    }
    return %orig;
}

- (void)scrollViewWillBeginDragging:(id)arg1 {
    %orig;
    [MSHookIvar<UITableView *>(self,"_tableView") endEditing:YES];
}
%end

%hook CMessageMgr
- (void)onNewSyncAddMessage:(CMessageWrap *)msgWrap {
    %orig;
    if (MSHookIvar<unsigned int>(msgWrap, "m_uiMessageType") == 49 &&
        [LFDefault boolForKey:LFSWITCH]) {
        WCPayInfoItem *item = [msgWrap m_oWCPayInfoItem];
        NSString *c2cNativeUrl = [item m_c2cNativeUrl];
        NSInteger len = [@"wxpay://c2cbizmessagehandler/hongbao/receivehongbao?" length];
        NSString *c2cNativeUrl2 = [c2cNativeUrl substringFromIndex:len];
        // 调用类方法的时候，使用
        NSDictionary *url_dic = [%c(WCBizUtil) dictionaryWithDecodedComponets:c2cNativeUrl2 separator:@"&"];
        if (url_dic.count <= 0) return;
        // 抢红包参数拼接
        NSMutableDictionary *mutable_dic = [%c(NSMutableDictionary) dictionary];
        [mutable_dic setObject:@"1" forKey:@"msgType"];
        [mutable_dic setObject:url_dic[@"sendid"] forKey:@"sendId"];
        [mutable_dic setObject:url_dic[@"channelid"] forKey:@"channelId"];
        // 2
        MMServiceCenter *mmserCent = [%c(MMServiceCenter) defaultCenter];
        Class ccmgr = [%c(CContactMgr) class];
        CContactMgr *contactMgr = [mmserCent getService:ccmgr];
        CContact *selfContact = [contactMgr getSelfContact];
        id displayName = [selfContact getContactDisplayName];
        [mutable_dic setObject:displayName forKey:@"nickName"];
        [mutable_dic setObject:[selfContact m_nsHeadImgUrl] forKey:@"headImg"];
        if (msgWrap) {
            NSString *nativeUrl = c2cNativeUrl;
            [mutable_dic setObject:nativeUrl forKey:@"nativeUrl"];
        }
        // 3
        NSString *nsUserName = MSHookIvar<NSString *>(msgWrap, "m_nsFromUsr");
        if (nsUserName) {
            [mutable_dic setObject:nsUserName forKey:@"sessionUserName"];
        }

        WeChatRedEnvolopParamQueue *shareInstance = [WeChatRedEnvolopParamQueue shareQueue];
        // 用来判断是否可以抢红包
        [mutable_dic setObject:@1 forKey:@"timingIdentifier"];
        [shareInstance enqueue:mutable_dic];

        // 拆红包拼接参数
        NSMutableDictionary *params =  [%c(NSMutableDictionary) dictionary];
        [params setObject:@"0" forKey:@"agreeDuty"];
        if ([MSHookIvar<NSString *>(msgWrap,"m_nsFromUsr") rangeOfString:@"@chatroom"].location != NSNotFound) {
            [params setObject:@"0" forKey:@"inWay"];
        } else {
            [params setObject:@"1" forKey:@"inWay"];
        }

        [params setObject:url_dic[@"channelid"] forKey:@"channelId"];
        [params setObject:@"1" forKey:@"msgType"];
        [params setObject:c2cNativeUrl forKey:@"nativeUrl"];
        [params setObject:url_dic[@"sendid"] forKey:@"sendId"];
        WCRedEnvelopesLogicMgr *redEvelopesLogicMgr = [[%c(MMServiceCenter) defaultCenter] getService:[%c(WCRedEnvelopesLogicMgr) class]];
        // 真正调用拆红包请求方法
        [redEvelopesLogicMgr ReceiverQueryRedEnvelopesRequest:params];
    }
}
%end

%hook WCRedEnvelopesLogicMgr
- (void)OnWCToHongbaoCommonResponse:(HongBaoRes *)arg1 Request:(id)arg2 {
    %orig;
    NSError *err;
    NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:arg1.retText.buffer options:NSJSONReadingMutableContainers error:&err];
    BOOL flag = (responseDict[@"receiveStatus"] && [responseDict[@"receiveStatus"] integerValue] == 0);
    if (arg1 != nil && arg2 != nil && arg1.cgiCmdid == 3 && flag) {
        NSString *timingIdentifier = responseDict[@"timingIdentifier"];
        NSMutableDictionary *param = [[WeChatRedEnvolopParamQueue shareQueue] getqueue];
        if (param && timingIdentifier && param[@"timingIdentifier"]) {
            [param setObject:timingIdentifier forKey:@"timingIdentifier"];
            WCRedEnvelopesLogicMgr *redEvelopesLogicMgr = [[%c(MMServiceCenter) defaultCenter] getService:[%c(WCRedEnvelopesLogicMgr) class]];

            CGFloat sleepTime = [[LFDefault objectForKey:LFWAITTIME] floatValue];
            if (sleepTime <= 0.3) sleepTime = 1.0;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(sleepTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                // 抢红包
                [redEvelopesLogicMgr OpenRedEnvelopesRequest:param];
            });
        }
    }
}
%end

